<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="pd.showSearch">
        <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="工序" prop="processId">
            <ProcessSearch :dataText="pd.dataText" @ok="selectQueryName"/>
          </el-form-item>
          <el-form-item label="绑定设备" prop="equipmentId">
            <el-input v-model="pd.queryParams.equipmentId" placeholder="请输入绑定设备" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" v-hasPermi="['wms:bom:add']" @click="handleAdd">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="pd.single" @click="handleUpdate"
                       v-hasPermi="['wms:bom:edit']">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="pd.multiple" @click="handleDelete"
                       v-hasPermi="['wms:bom:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wms:bom:export']">
              导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="pd.loading" :data="pd.bomProcessList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['wms:bom:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['wms:bom:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="工序" align="center" prop="processId"/>
        <el-table-column label="工序名称" align="center" prop="processName"/>
        <el-table-column label="顺序" align="center" prop="sort"/>
        <el-table-column label="绑定设备" align="center" prop="equipmentId"/>
        <el-table-column label="是否启用" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="创建部门" align="center" prop="createDept"/>
        <el-table-column label="备注" align="center" prop="remark"/>
        <el-table-column label="创建者" align="center" prop="createBy"/>
        <el-table-column label="创建时间" align="center" prop="createTime"/>
        <el-table-column label="更新者" align="center" prop="updateBy"/>
        <el-table-column label="更新时间" align="center" prop="updateTime"/>
      </el-table>

      <Pagination v-show="pd.total>0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                  v-model:limit="pd.queryParams.pageSize" @pagination="getList"/>
    </el-card>
    <!--     添加或修改测试主从对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="660px" append-to-body>
      <el-form ref="bomProcessFormRef" :model="pd.processForm" :rules="pd.rules" label-width="80px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="工序" prop="processId">
              <ProcessSearch :dataText="pd.formText" @ok="selectFormProcessId"/>
            </el-form-item>
            <el-form-item label="顺序" prop="sort">
              <el-input v-model="pd.processForm.sort" placeholder="请输入顺序"/>
            </el-form-item>
            <el-form-item label="绑定设备" prop="equipmentId">
              <el-input v-model="pd.processForm.equipmentId" placeholder="请输入绑定设备"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="是否启用" prop="status">
              <el-select v-model="pd.processForm.status" placeholder="请选择是否启用">
                <el-option v-for="dict in sys_status" :key="dict.value" :label="dict.name" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="pd.processForm.remark" type="textarea" placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="pd.dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<!--物料清单工艺明细-->
<script setup name="BomProcess" lang="ts">
import {
  BomProcessVO,
  BomVO,
  listBomProcess,
  getBomProcess,
  updateBom,
  addBom,
  delBomProcess,
  addBomProcess, updateBomProcess
} from "@/views/wms/bom/api";
import ProcessSearch from "@/views/wms/process/search.vue";
import {ProcessVO, listProcess} from "@/views/wms/process/api";

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const { sys_status } = toRefs<any>(proxy?.useDict('sys_status' ));

const pd = reactive({
  bomProcessList: <BomProcessVO[]>([]),
  processList: <ProcessVO[]>([]),
  buttonLoading: false,
  dataText: "请选择工序名称",
  formText: "请选择工序名称",
  loading: true,
  processIds: <Array<string | number>>([]),
  isExpandAll: true,
  showSearch: true,
  single: true,
  multiple: true,
  total: 0,
  deletes: <BomProcessVO[]>([]),
  processForm: <BomProcessVO>{},
  dialog: <DialogOption>{
    visible: false,
    title: ''
  },
  queryParams: <BomProcessVO>{
    pageNum: 1,
    pageSize: 10,
    id: parseInt(route.query.id as string),
    processId: undefined,
    equipmentId: undefined,
  },
  rules: <ElFormRules>{
    processId: [{required: true, message: "工序不能为空", trigger: "blur"}],
    sort: [{required: true, message: "顺序不能为空", trigger: "blur"}],
    status: [{required: true, message: "状态不能为空", trigger: "blur"}],
  }
})

/** 查询列表 */
async function getList() {
  pd.loading = true;
  const result = await listProcess();
  pd.processList = result.rows;
  const res = await listBomProcess(pd.queryParams);
  pd.bomProcessList = res.rows;
  pd.bomProcessList.forEach(bomProcess => {
    pd.processList.forEach(process => {
      if (bomProcess.processId === process.id) {
        bomProcess.processName = process.name;
      }
    })
  });
  pd.total = res.total;
  pd.loading = false;
}

function selectFormProcessId(value: ProcessVO[]) {
  pd.formText = value[0].name as string;
  pd.processForm.processId = value[0].id;
}

function selectQueryName(value: ProcessVO[]) {
  pd.dataText = value[0].name as string;
  pd.queryParams.processId = value[0].id;
}

/** 多选框选中数据 */
function handleSelectionChange(selection: BomProcessVO[]) {
  pd.deletes = selection;
  pd.processIds = selection.map(item => item.processId) as (string | number)[];
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.processForm.status = "0";
  pd.dialog.visible = true;
  pd.dialog.title = "新增物品工序";
}

/** 修改按钮操作 */
async function handleUpdate(row?: BomProcessVO) {
  reset();
  if (row && row.id) {
    pd.processForm = {
      id: row?.id,
      processId: row?.processId,
      sort: row?.sort,
    };
  }else{
    pd.processForm ={
      id:pd.deletes[0].id,
      processId:pd.deletes[0].processId,
      sort:pd.deletes[0].sort,
    }
  }
  const res = await getBomProcess(pd.processForm);
  Object.assign(pd.processForm, res.data);
  pd.processList.forEach(process => {
    if (pd.processForm.processId === process.id) {
      pd.formText = process.name as string;
    }
  });
  pd.dialog.visible = true;
  pd.dialog.title = "修改物品工序";
}

/** 删除按钮操作 */
async function handleDelete(row?: BomProcessVO) {
  if (pd.deletes.length > 0) {
    Object.assign(pd.processForm, pd.deletes[0]);
    pd.processForm.children = pd.deletes;
  } else if (row) {
    pd.processIds = [row.processId as string | number];
    Object.assign(pd.processForm, row);
    pd.processForm.children = [row];
  }
  await proxy?.$modal.confirm('是否确认删除工序为"' + pd.processIds + '"的数据项？').finally(() => pd.loading = false);
  await delBomProcess(pd.processForm);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 提交表单 */
function submitForm() {
  (proxy?.$refs['bomProcessFormRef'] as any).validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.dialog.title === "修改物品工序") {
        await updateBomProcess(pd.processForm).finally(() => {
          pd.buttonLoading = false;
          proxy?.$modal.msgSuccess("修改成功");
        });
      } else {
        await addBomProcess(pd.processForm).finally(() => {
          pd.buttonLoading = false;
          proxy?.$modal.msgSuccess("新增成功");
        });
      }
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 表单重置 */
function reset() {

  pd.processForm = {
    id: parseInt(route.query.id as string),
    processId: undefined,
    sort: undefined,
    equipmentId: undefined,
    status: '',
    createDept: undefined,
    remark: '',
  };
  pd.formText = "请选择工序名称";
  if ((proxy?.$refs['bomFormRef'] as any) !== undefined) {
    (proxy?.$refs['bomFormRef'] as any).resetFields();
  }


}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  pd.dataText = "请选择工序名称";
  (proxy?.$refs['queryFormRef'] as any).resetFields();
  getList();
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('wms/bom/export', {
    ...pd.queryParams
  }, `bom_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>


<style scoped>

</style>
